<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 描述性数据基类
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Abstract_Metas extends Widget
{
    /**
     * 锚点id
     *
     * @access protected
     * @return string
     */
    protected function ___theId()
    {
        return $this->type . '-' . $this->mid;
    }

    /**
     * icon
     *
     * @access protected
     * @return string
     */
    protected function ___icon()
    {
		$icon = $this->pic;
		if($icon){
		    strpos($icon, '://') === FALSE && $icon = $this->options->uploadUrl . $icon;
		}else{
			$icon = $this->options->staticUrl('images/no-image.png', false);
		}
        return $icon;
    }
	
    /**
     * 获取原始查询对象
     *
     * @access public
     * @return Db_Query
     */
    public function select()
    {
        return $this->db->select()
		    ->from('table.metas');
    }

    /**
     * 插入一条记录
     *
     * @access public
     * @param array $values 记录结构数组
     * @return integer
     */
    public function insert(array $values)
    {
        /** 构建插入结构 */
        $metas = array(
            'parent'        =>  empty($values['parent']) ? 0 : intval($values['parent']),
			'name'          =>  empty($values['name']) ? '' : htmlspecialchars($values['name']),
            'type'          =>  empty($values['type']) ? 'tag' : $values['type'],
			/** 避免冲突 */
			'alias'         =>  Common::aliasName(),
            'order'         =>  empty($values['order']) ? 0 : intval($values['order']),
			'template'      =>  empty($values['template']) ? '' : $values['template'],
            'contentsNum'   =>  empty($values['contentsNum']) ? 0 : intval($values['contentsNum']),
			'pic'           =>  empty($values['pic']) ? '' : $values['pic'],
            'description'   =>  empty($values['description']) ? '' : $values['description'],
        );

        if (!empty($values['mid'])) {
            $metas['mid'] = $values['mid'];
        }
		
		/** 插件接口 */
		//HOOK $metas | PLUG_Abstract_Metas_Insert($values, $this);

		/** 首先插入部分数据 */
        $insertId = $this->db->insert('table.metas')
		    ->values($metas)
			->lastInsertId();
			
        if ($insertId > 0 ) {

			/** 更新缩略名 */
			$this->applyAlias(empty($values['alias']) ? $insertId : $values['alias'], $insertId);
        }
		
        return $insertId;
    }

    /**
     * 更新记录
     *
     * @access public
     * @param $mid 记录mid
     * @param array $values 记录更新结构数组
     * @return integer
     */
    public function update($mid, array $values)
    {		
        /** 构建插入结构 */
        $update = array(
            'parent'        =>  empty($values['parent']) ? 0 : intval($values['parent']),
			'name'          =>  empty($values['name']) ? '' : htmlspecialchars($values['name']),
            'type'          =>  empty($values['type']) ? 'tag' : $values['type'],
			/** 避免冲突 */
			'alias'         =>  Common::aliasName(),
            'order'         =>  empty($values['order']) ? 0 : intval($values['order']),
			'template'      =>  empty($values['template']) ? '' : $values['template'],
            'contentsNum'   =>  empty($values['contentsNum']) ? 0 : intval($values['contentsNum']),
			'pic'           =>  empty($values['pic']) ? '' : $values['pic'],
            'description'   =>  empty($values['description']) ? '' : $values['description'],
        );

        $meta = array();
        foreach ($values as $key => $val) {
            if (array_key_exists($key, $update)) {
                $meta[$key] = $update[$key];
            }
        }
		
		//HOOK $meta | PLUG_Abstract_Metas_Update($values, $this);
		
        $updateRows = $this->db->update('table.metas')
		    ->where('mid = ?', $mid)
		    ->values($meta)
		    ->affectedRows();

		/** 更新缩略名 */
        $this->applyAlias(empty($values['alias']) ? $mid : $values['alias'], $mid);

        return $updateRows;
    }
	
    /**
     * 删除记录
     *
     * @access public
     * @param $mid 记录mid
     * @return integer
     */
    public function delete($mid)
    {
		/** 插件接口 */
		//HOOK PLUG_Abstract_Metas_Delete($mid, $this);
		
        return $this->db->delete('table.metas')
		    ->where('mid = ?', $mid)
			->affectedRows();
    }
	
    /**
     * 通用过滤器
     *
     * @access public
     * @param array $value 需要过滤的行数据
     * @return array
     */
    public function filter(array $value)
    {
		if (isset($value['mid'], $value['type'], $value['alias'])) {	
            //生成静态链接
            $type = $value['type'];
            $routeExists = (NULL != Router::get($type));
            $tmpAlias = $value['alias'];
            $value['alias'] = urlencode($value['alias']);

            $value['permalink'] = $routeExists ? Router::url($type, $value, $this->options->index) : '#';

            $value['alias'] = $tmpAlias;
		}
		//HOOK $value | PLUG_Abstract_Metas_Filter($value, $this);
		
        return $value;
    }

    /**
     * 将每行的值压入堆栈
     *
     * @access public
     * @param array $value 每行的值
     * @return array
     */
    public function push(array $value)
    {
        $value = $this->filter($value);
        return parent::push($value);
    }

    /**
     * 应用缩略名
     *
     * @access public
     * @param string $alias 缩略名
     * @param mixed $mid 记录mid
     * @return string
     */
    public function applyAlias($alias, $mid)
    {

	    //HOOK $alias | PLUG_Abstract_Metas_Alias($alias, $this);
		
		$count = 1;
		$pass = true;
		
        /** 判断是否在数据库中已经存在 */
        while (true) {
			$row = $this->db->select('mid')
			    ->from('table.metas')
                ->where('alias = ?', $alias)
			    ->fetchRow();
			if($row){
				if($row['mid'] != $mid){
                    $alias = $alias . '-' . $count;
                    $count ++;
			    } else {
					$pass = false;
					break;
				}
			} else {
				break;
			}
        }
		
		$pass && $this->db->update('table.metas')
		    ->where('mid = ?', $mid)
			->values(array('alias'=>$alias))
			->affectedRows();

        return $alias;
    }
	
    /**
     * 获取最大排序
     * 
     * @param mixed $type 
     * @param int $parent 
     * @access public
     * @return integer
     */
    public function getMaxOrder($type, $parent = 0)
    {
        return $this->db->select(array('MAX(order)' => 'maxOrder'))
		    ->from('table.metas')
		    ->where('type = ? AND parent = ?', $type, $parent)
			->fetchObject()
			->maxOrder;
    }

    public function getByName($name, $type = 'tag')
    {
        return $this->db->select()
		    ->from('table.metas')
			->where('type = ? AND name = ?', $type, $name)
			->fetchRow();
    }
	
    /**
     * 获取页面偏移
     *
     * @access protected
     * @param string $column 字段名
     * @param integer $offset 偏移值
     * @param string $type 类型
     * @param integer $pageSize 分页值
     * @return integer
     */
    protected function getPageOffset($column, $offset, $type, $pageSize = 20)
    {
        $count = $this->db->select(array('COUNT(table.metas.mid)' => 'num'))
		    ->from('table.metas')
            ->where("table.metas.{$column} > {$offset}")
            ->where("table.metas.type = ?", $type)
		    ->fetchObject()->num + 1;

        return ceil($count / $pageSize);
    }
}
